import { Button } from '@components/Button'
import {
	AppLoadingState,
	useAppLoadingContext,
} from '@context/AppLoadingContext'
import { Box, Stack } from '@highlight-run/ui/components'
import MuxPlayer from '@mux/mux-player-react'
import { CSSProperties, useEffect, useRef, useState } from 'react'

const CanvasPage = function () {
	const { setLoadingState } = useAppLoadingContext()

	useEffect(() => {
		setLoadingState(AppLoadingState.LOADED)
	}, [setLoadingState])

	const ref = useRef<HTMLDivElement>(null)
	const [mode, setMode] = useState<
		'BigBuckBunny' | 'canvas' | 'webcam' | 'mux'
	>('webcam')
	const [numCanvases, setNumCanvases] = useState<number>(0)
	const [canvasStyle, setCanvasStyle] = useState<CSSProperties>()

	const onMouseMove = () => {
		setCanvasStyle((s) => ({
			display: 'block',
			width: Number(s?.width || 500) + (Math.random() < 0.5 ? 1 : -1) * 1,
			height:
				Number(s?.height || 500) + (Math.random() < 0.5 ? 1 : -1) * 1,
			touchAction: 'none',
			outline: 'none',
			cursor: `url(), pointer`,
			background: `linear-gradient(rgb(${255 * Math.random()}, ${
				255 * Math.random()
			}, ${255 * Math.random()}) 0%, rgb(${255 * Math.random()}, ${
				255 * Math.random()
			}, ${255 * Math.random()}) 100%)`,
		}))
	}

	useEffect(() => {
		if (mode !== 'webcam') return
		const video = document.querySelector('#webcam')! as any
		navigator.mediaDevices
			?.getUserMedia({ video: true, audio: false })
			.then((localMediaStream) => {
				console.log('setting up video localMediaStream')
				if ('srcObject' in video) {
					video.srcObject = localMediaStream
				} else {
					video.src = window.URL.createObjectURL(
						localMediaStream as any,
					)
				}
				video.play()
			})
			.catch((err) => {
				console.error(`video available`, err)
			})
	}, [mode])

	useEffect(() => {
		const canvases = ref.current?.getElementsByTagName('canvas')
		if (!canvases) return
		for (const canvas of canvases) {
			const rand = Math.random()
			if (rand < 0.25) {
				const ctx = canvas.getContext('bitmaprenderer')!
				const img = ref.current
					?.getElementsByClassName('sample-image')
					.item(0) as HTMLImageElement
				img.onload = function () {
					createImageBitmap(img, {
						resizeQuality: 'low',
						resizeWidth: 128,
						resizeHeight: 128,
					}).then((bitmap) => {
						ctx.transferFromImageBitmap(bitmap)
					})
				}
			} else if (rand < 0.5) {
				const gl = canvas.getContext('webgl')
				if (!gl) continue
				gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight)
				for (let i = 0; i < 100; i++) {
					setInterval(() => {
						const color = [
							Math.random(),
							Math.random(),
							Math.random(),
						]
						gl.clearColor(color[0], color[1], color[2], 1.0)
						gl.clear(gl.COLOR_BUFFER_BIT)
					}, i)
				}
			} else if (rand < 0.75) {
				const gl2 = canvas.getContext('webgl2')
				if (!gl2) continue
				gl2.viewport(
					0,
					0,
					gl2.drawingBufferWidth,
					gl2.drawingBufferHeight,
				)
				for (let i = 0; i < 100; i++) {
					setInterval(() => {
						const color = [
							Math.random(),
							Math.random(),
							Math.random(),
						]
						gl2.clearColor(color[0], color[1], color[2], 1.0)
						gl2.clear(gl2.COLOR_BUFFER_BIT)
					}, i)
				}
			} else {
				const ctx = canvas.getContext('2d')
				if (!ctx) continue
				for (let i = 0; i < 1000; i++) {
					setInterval(() => {
						const randomColor = Math.floor(
							Math.random() * 16777215,
						).toString(16)

						ctx.fillStyle = `#${randomColor}`
						ctx.beginPath()
						ctx.arc(
							Math.random() * canvas.width,
							Math.random() * canvas.height,
							10,
							0,
							2 * Math.PI,
						)
						ctx.fill()
					}, i)
				}
			}
		}
	}, [numCanvases])

	return (
		<Box ref={ref} width="full" height="full">
			<Box display="flex" width="full">
				<Stack>
					<Box display="flex" gap="4">
						<Button
							trackingId="canvasIncrement"
							onClick={() => setNumCanvases((n) => n + 1)}
						>
							Add Canvas
						</Button>
						<Button
							trackingId="modeIncrement"
							onClick={() => {
								setMode((m) => {
									if (m === 'BigBuckBunny') {
										return 'canvas'
									}
									if (m === 'canvas') {
										return 'webcam'
									}
									if (m === 'webcam') {
										return 'mux'
									}
									return 'BigBuckBunny'
								})
							}}
						>
							Change Mode
						</Button>
					</Box>
					<Box border="dividerStrong">
						{mode === 'BigBuckBunny' ? (
							<video
								width={640}
								height={480}
								preload="metadata"
								autoPlay={true}
								crossOrigin="anonymous"
								src="https://static.highlight.io/dev/BigBuckBunny.mp4?expires=123&signature=a1b2c3&x-amz-security-token=foo&bar=baz"
							></video>
						) : mode === 'canvas' ? (
							<Box>
								{Array(numCanvases)
									.fill(0)
									.map((_, i) => (
										<canvas
											id={`canvas-${i}`}
											key={`canvas-${i}`}
											style={canvasStyle}
											onMouseMove={onMouseMove}
											tabIndex={8888}
											width={640}
											height={480}
											className=":hover"
										/>
									))}
								<img
									className="sample-image"
									src="https://upload.wikimedia.org/wikipedia/commons/a/a4/Fiore_con_petali_arancioni_SVG.svg"
									width={512}
									height={512}
									alt="sample-image"
								/>
							</Box>
						) : mode === 'webcam' ? (
							<video
								autoPlay
								muted
								playsInline
								id="webcam"
								width={640}
								height={480}
							></video>
						) : mode === 'mux' ? (
							<MuxPlayer
								playbackId="DS00Spx1CV902MCtPj5WknGlR102V5HFkDe"
								metadata={{
									video_id: 'video-id-123456',
									video_title: 'Bick Buck Bunny',
									viewer_user_id: 'user-id-bc-789',
								}}
								streamType="on-demand"
							/>
						) : null}
					</Box>
				</Stack>
			</Box>
		</Box>
	)
}
export default CanvasPage
